package com.hsogoo.collate.service;

import com.hsogoo.collate.domain.DynamicQuery;
import com.hsogoo.collate.mapper.DynamicMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorCompletionService;

/**
 * 采用此类在springBatch的tasklet中不能正确切换动态数据源
 * 原因暂时还没找到，可能是线程切换的问题引起
 * 所以先另起线程执行动态数据源操作
 * @Author huangsaigang
 * Created @2019-11-06.
 */
@Slf4j
@Service
public class AsyncDynamicQueryService {

    @Autowired
    private Executor executor;
    @Autowired
    private DynamicMapper dynamicMapper;


    public List<Map<String, Object>> dynamicQuery(DynamicQuery query){

        ExecutorCompletionService<List<Map<String, Object>>> completionService = new ExecutorCompletionService<>(executor);
        completionService.submit(new DynamicQueryTask(dynamicMapper, query));
        List<Map<String, Object>> result = null;
        try {
            result = completionService.take().get();
        }catch (Exception e){
            log.error("executorCompletionService take error", e);
            return null;
        }
        return result;
    }


}
